package com.example.demo.controller;

import com.example.demo.model.Category;
import com.example.demo.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Slf4j
//@Controller
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    public ICategoryService categoryService;

//    查询所有
    @GetMapping("/")
    public List<Category> getAll(){
        return categoryService.getAllCategories();
    }

//    添加分类饮品
    @PostMapping("/")
    public Category addNewCategory(@RequestBody @Valid Category category,
                                    BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            for (ObjectError error : bindingResult.getAllErrors()){
                log.error(error.toString());
            }
            return null;
        }else {
            log.info("新增分类：{}",category);
            categoryService.addNewCategory(category);
            return category;
        }
    }

//    编辑分类饮品
    @PutMapping("/")
    public Category modifyCategory(@RequestBody Category request){
//        查看有无分类
        Category category=categoryService.getCategoryById(request.getId());
//        把要修改的内容和category对应
        BeanUtils.copyProperties(request,category);
//        更新数据库
        categoryService.updateCategory(category);
        return category;
    }

//    删除分类饮品
    @DeleteMapping("/{id}")
    public String deleteCategory(@PathVariable Integer id){
        log.info("要删除的分类id：{}",id);
        categoryService.deleteCategory(id);
        return "删除成功";
    }
}
